//
//  RequestBase.m
//
//  Created by 王越 on 15/6/30.
//  Copyright (c) 2015年 王越. All rights reserved.
//

#import "RequestBase.h"
#import "UserInfo.h"
#import "iTools.h"
#import "RequestConfig.h"
//#import "CBCDef.h"
#import "RegisterRequest.h"
#if __has_include(<AFNetworking/AFNetworking.h>)
#import <AFNetworking/AFNetworking.h>
#else
#import "AFNetworking.h"
#endif
#define KEYUSERINFO  @"keyUserInfo"
@interface RequestBase ()<UIAlertViewDelegate>

typedef enum {
    GET,
    POST,
    DOWNLOAD,
    UPLOAD
}RequestType;//联网类型

/**联网类型*/
@property (nonatomic,assign) RequestType requestType;

/**当前访问地址*/
@property (nonatomic, retain) NSString *url;
/**下载文件路径*/
@property (nonatomic, strong) NSString *downloadFilePath;
/**上传参数*/
@property (nonatomic, retain) NSDictionary *postBody;
/**表单数据*/
@property (nonatomic, retain) NSDictionary *formData;
/**回调*/
@property (nonatomic, assign) id<RequestBaseDelegate> delegate;

/**下载文件路径*/
@property (nonatomic, strong) NSObject *responseObject;
/**网络请求是否取消*/
@property (nonatomic,assign) BOOL isCancelRequest;

/**是否自动登录*/
@property (nonatomic,assign) BOOL isAutoLogin;

@end

@implementation RequestBase

/**
 *  get联网方法
 *
 *  @param url      <#url description#>
 *  @param postBody <#postBody description#>
 *  @param delegate <#delegate description#>
 */
- (void)doGetRequest:(NSString *)url
            PostBody:(NSDictionary *)postBody
            Delegate:(id<RequestBaseDelegate>)delegate
{
    self.requestType = GET;
    self.url = url;
    self.postBody = postBody;
    self.delegate = delegate;
    [self onStartRequest];
}

/**
 *  post联网方法
 *
 *  @param url      <#url description#>
 *  @param postBody <#postBody description#>
 *  @param delegate <#delegate description#>
 */
- (void)doPostRequest:(NSString *)url
             PostBody:(NSDictionary *)postBody
             Delegate:(id<RequestBaseDelegate>)delegate
{
    self.requestType = POST;
    self.url = url;
    self.postBody = postBody;
    self.delegate = delegate;
    [self onStartRequest];
}

/**
 表单提交数据
 
 @param url      <#url description#>
 @param postBody <#postBody description#>
 @param data     data description
 */
- (void)doPostFormDataRequest:(NSString *)url
                     PostBody:(NSDictionary *)postBody
                     FormData:(NSDictionary *)data
                     Delegate:(id<RequestBaseDelegate>)delegate
{
    self.requestType = UPLOAD;
    self.url = url;
    self.postBody = postBody;
    self.formData = data;
    self.delegate = delegate;
    [self onStartRequest];
}

/**
 下载文件
 
 @param url              下载地址
 @param downloadFilePath 保存路径
 @param delegate         代理
 */
- (void)doDownlodFileRequest:(NSString *)url
                        Path:(NSString *)downloadFilePath
                    Delegate:(id<RequestBaseDelegate>)delegate
{
    self.requestType = DOWNLOAD;
    self.url = url;
    self.downloadFilePath = downloadFilePath;
    self.delegate = delegate;
    [self onStartRequest];
}

/*
 * 开始联网
 */
- (void)onStartRequest
{
    self.dialogMessage = @"获取数据中...";
    self.isCancel = NO;
    self.isCancelRequest = NO;
//    [iTools hideMBLoading];
    //显示锁定视图
    if(!self.isHiddenDialog){
//        [iTools showMBLoadingAnimate:@"" detailText:self.dialogMessage];
    }
    switch (self.requestType) {
        case GET:
            [self onGetRequest];
            break;
        case POST:
            [self onPostRequest];
            break;
        case UPLOAD:
            [self onUploadRequest];
            break;
        case DOWNLOAD:
            [self onDownloadRequest];
            break;
        default:
            break;
    }
}


/**
 获取Http Manager

 @return Http Manager
 */
-(AFHTTPSessionManager*)getManager
{
    AFHTTPSessionManager* manager = [AFHTTPSessionManager manager];
    // 声明上传的是json格式的参数，需要你和后台约定好，不然会出现后台无法获取到你上传的参数问题
    manager.requestSerializer = [AFHTTPRequestSerializer serializer]; // 上传普通格式
    // 超时时间
    manager.requestSerializer.timeoutInterval = NETWORK_TIME_OUT;
    //设置请求头
    [manager.requestSerializer setValue:[RequestConfig ContentType] forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:[RequestConfig getXClient] forHTTPHeaderField:@"X-Client"];
    [manager.requestSerializer setValue:[RequestConfig getCOOKIE] forHTTPHeaderField:@"COOKIE"];
    NSLog(@"cookie is:%@",[RequestConfig getCOOKIE]);
    // 声明获取到的数据格式
    manager.responseSerializer = [AFHTTPResponseSerializer serializer]; // CBCN不会解析,数据是data，需要自己解析
    return manager;
}

/**
 get连网获取数据
 */
-(void)onGetRequest
{
    // 创建请求类
    AFHTTPSessionManager* manager = [self getManager];
    
    //当前类的引用
    __weak typeof(self) safeSelf = self;
    //开始联网
    [manager GET:self.url parameters:self.postBody progress:^(NSProgress * _Nonnull uploadProgress) {
        [safeSelf onRequestProgress:uploadProgress];
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [safeSelf onRequestSuccess:responseObject];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [safeSelf onRequestFailed:[error localizedDescription]];
    }];
}

/**
 post连网获取数据
 */
-(void)onPostRequest
{
    // 创建请求类
    AFHTTPSessionManager* manager = [self getManager];
    //当前类的引用
    __weak typeof(self) safeSelf = self;
    //开始联网
    [manager POST:self.url parameters:self.postBody progress:^(NSProgress * uploadProgress) {
        [safeSelf onRequestProgress:uploadProgress];
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [safeSelf onRequestSuccess:responseObject];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [safeSelf onRequestFailed:[error localizedDescription]];
    }];
}


/**
 连网获取数据
 */
-(void)onUploadRequest
{
    // 创建请求类
    AFHTTPSessionManager* manager = [self getManager];

    //当前类的引用
    __weak typeof(self) safeSelf = self;
    //开始联网
    [manager POST:self.url parameters:self.postBody constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if(safeSelf.formData && safeSelf.formData.count > 0){
            NSEnumerator * enumeratorKey = [safeSelf.formData keyEnumerator];
            //快速枚举遍历所有KEY的值
            for (NSString *key in enumeratorKey) {
                NSString* filePath = [safeSelf.formData objectForKey:key];
                NSURL* fileUrl = [NSURL fileURLWithPath:filePath];
                NSError *error;
                [formData appendPartWithFileURL:fileUrl name:key error:&error];
                if(error){
                    [safeSelf onRequestFailed:[error localizedDescription]];//请求失败
                }
            }
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        [safeSelf onRequestProgress:uploadProgress];
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [safeSelf onRequestSuccess:responseObject];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [safeSelf onRequestFailed:[error localizedDescription]];
    }];
}

/**
 下载文件
 */
-(void)onDownloadRequest
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.url]];
    
    __weak typeof(self) safeSelf = self;
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        [safeSelf onRequestProgress:downloadProgress];
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        return [NSURL fileURLWithPath:self.downloadFilePath];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
    }];
    [downloadTask resume];
}


/**
 联网进度

 @param progress <#progress description#>
 */
-(void)onRequestProgress:(NSProgress *)progress
{
    //调用子类实现的方法
    if(self.delegate && [self.delegate respondsToSelector:@selector(progress:)]){
        [self.delegate progress:progress];
    }
}

/**
 联网成功后的处理方法
 @param data 返回的数据
 */
-(void)onRequestSuccess:(NSData *)data
{
    //解析成功返回的数据
    NSError *error;;
    NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    if (!error) {
        //解析共用数据
        @try {
            self.responseMessage = [dic valueForKey:HTTP_RESPONSE_MSG];
            if([[dic valueForKey:HTTP_RESPONSE_CODE] isKindOfClass:[NSString class]]){
                self.responseCode = [[dic valueForKey:HTTP_RESPONSE_CODE] intValue];
            }
        }
        @catch (NSException *exception) {

        }

        //调用子类实现的解析结构体的方法
        if(self.delegate && [self.delegate respondsToSelector:@selector(parserData:)]){
//            self.responseObject = [self.delegate parserData:dic];
            [self.delegate parserData:dic];
        }
        //判断状态码
        if(self.responseCode && self.responseCode == SUCCESS_OPERATION){
            if(!self.isCancelRequest){//判断是否已经取消联网
                //回调成功
                if(self.delegate && [self.delegate respondsToSelector:@selector(requestSuccess:)]){
                    [self.delegate requestSuccess:self.responseObject];
                }
            }
            //隐藏滚动条
//            [iTools hideMBLoading];
        }else if(self.responseCode && self.responseCode == SessionFailure){
            if(!self.isAutoLogin){
                [self autoLogin];
            }else{
                //自动注册
                [self autoRegister];
//                [self onRequestFailed:self.responseMessage];
            }
        }else{
            [self onRequestFailed:self.responseMessage];
        }
    }else{
        NSString *result = [[NSString alloc] initWithData:data  encoding:NSUTF8StringEncoding];
        if([result isEqualToString:@"success"]){
            [self.delegate requestSuccess:nil];
//            [iTools hideMBLoading];
        }
        else{
            [self onRequestFailed:[error localizedDescription]];
        }

    }
}

-(void)autoLogin
{

    self.isAutoLogin = YES;
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSData *data = [user objectForKey:KEYUSERINFO];
    UserInfo* userInfo  = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    
    NSString* url = [NSString stringWithFormat:@"%@/api/login_account/",[iTools ServerHost]];
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:
                         userInfo.username ,@"account",
                         userInfo.password ,@"password",
                         nil];
    
    // 创建请求类
    AFHTTPSessionManager* manager = [self getManager];
    //当前类的引用
    __weak typeof(self) safeSelf = self;
    //开始联网
    [manager POST:url parameters:dic progress:^(NSProgress * uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [safeSelf onStartRequest];
        //自动刷新空间界面
//        NSMutableDictionary *nsDic = [[NSMutableDictionary alloc]init];
//        [nsDic setValue:@"刷新页面" forKey:@"message"];
//        [[NSNotificationCenter defaultCenter]postNotificationName:FlushTabNotification object:nsDic];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [safeSelf onRequestFailed:[error localizedDescription]];
    }];
}


-(void)autoRegister{
    //当前类的引用
    __weak typeof(self) safeSelf = self;
    RegisterRequest *registerRequest = [[RegisterRequest alloc]init];
    [registerRequest startRequest:^(NSObject *o) {
        if(nil != o){
            NSData *data = [NSKeyedArchiver archivedDataWithRootObject:o];
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            [userDefaults setObject:data forKey:KEYUSERINFO];
            [userDefaults synchronize];
        }
    } fail:^(NSObject *o) {
        if(o){
            NSString* message = (NSString*)o;
            [safeSelf onRequestFailed:message];
        }else{
            [safeSelf onRequestFailed:@"联网竟然失败了，还没有返回错误信息！😢"];
        }
    }];
}




/**
 联网失败

 @param message 错误信息
 */
-(void)onRequestFailed:(NSString *)message
{
    //隐藏滚动条
//    [iTools hideMBLoading];
    //判断是否是主动取消联网
    if(!self.isCancelRequest){
        if(self.delegate && [self.delegate respondsToSelector:@selector(requestFailed:)]){
            [self.delegate requestFailed:message];
        }else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NETWORK_MESSAGE_NAME
                                                            message:message
                                                           delegate:self
                                                  cancelButtonTitle:@"重试"
                                                  otherButtonTitles:@"取消", nil];
            [alert show];
        }
    }
}

/**
 取消联网
 */
-(void)onRequestCancel
{
    self.isCancelRequest = YES;
    if(self.delegate && [self.delegate respondsToSelector:@selector(requestCancel)]){
        [self.delegate requestCancel];
    }
}

/**
 重试对话框的按钮响应
 */
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 0){
        [self onStartRequest];
    }
}

/**
 资源释放
 */
-(void)dealloc
{
    if(!self.isHiddenDialog){
//        [iTools hideMBLoading];
    }
}


@end
